<template>
  <el-dialog
    :title="this.type == 1 ? '创建标签' : '修改标签'"
    :visible.sync="dialogVisible"
    width="50%"
    @close="handelClose">
    <el-form :model="Form" :rules="rules" ref="fromRef" label-width="100px">
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="Form.name"></el-input>
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-color-picker
          v-model="Form.color"
          :predefine="predefineColors"></el-color-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addTagData">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addAssetsTag,
  editAssetsTag,
  getAssetsTagById
} from '@/api/assets/configuration.js'
export default {
  data() {
    return {
      dialogVisible: false,
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)'
      ],
      Form: {
        tagGroupId: '',
        name: '',
        color: '#1BE161'
      },
      rules: {
        name: [
          { required: true, message: '标签名称', trigger: 'blur' }
        ]
      },
      id: '',
      type: ''
    }
  },
  methods: {
    init(val, flag, type) {
      this.type = type
      if (type === 1) { // 新增
        this.Form.tagGroupId = val.id
      } else { // 修改
        this.id = val
        getAssetsTagById({ id: this.id }).then((res) => {
          this.Form.name = res.data.name
          this.Form.color = res.data.color
          this.Form.tagGroupId = res.data.tagGroupId
        })
      }
      this.dialogVisible = flag
    },
    addTagData() {
      this.$refs.fromRef.validate(valid => {
        if (!valid) return
        if (this.type === 1) { // 新增
          addAssetsTag(this.Form).then((res) => {
            this.dialogVisible = false
            this.$emit('addTag')
          })
        } else { // 修改
          const data = {
            id: this.id,
            tagGroupId: this.Form.tagGroupId,
            name: this.Form.name,
            color: this.Form.color
          }
          editAssetsTag(data).then((res) => {
            this.dialogVisible = false
            this.$emit('addTag')
          })
        }
      })
    },
    handelClose() {
      this.$refs.fromRef.resetFields()
    }
  }
}
</script>

<style scoped>
</style>
